package org.jeecg.modules.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xkcoding.http.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.dto.DbanInformationDto;
import org.jeecg.modules.system.entity.DbanAuthRecord;
import org.jeecg.modules.system.entity.DbanFileNginx;
import org.jeecg.modules.system.entity.DbanInfoStatusEnum;
import org.jeecg.modules.system.entity.DbanInformation;
import org.jeecg.modules.system.mapper.DbanAuthRecordMapper;
import org.jeecg.modules.system.mapper.DbanFileNginxMapper;
import org.jeecg.modules.system.mapper.DbanInformationMapper;
import org.jeecg.modules.system.service.IDbanInformationService;
import org.jeecg.modules.system.util.FileUtils;
import org.jeecg.modules.system.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class DbanInformationServiceImpl extends MPJBaseServiceImpl<DbanInformationMapper, DbanInformation> implements IDbanInformationService {

    @Resource
    private DbanInformationMapper dbanInformationMapper;
    @Resource
    private DbanFileNginxMapper dbanFileNginxMapper;
    @Value("${nginx.file.dir}")
    private String nginxFileDir;
    @Value("${nginx.dir}")
    private String nginxDir;
    @Resource
    private DbanAuthRecordMapper dbanAuthRecordMapper;
    @Autowired
    private SysBaseApiImpl sysBaseApi;

    /**
     * 添加或者编辑前的幂等处理
     */
    @Override
    public List<DbanInformation> checkRepeat(DbanInformation dbanInformationParam) {
        String type = dbanInformationParam.getType();
        String fiveOneType = dbanInformationParam.getFiveOneType();
        String name = dbanInformationParam.getName().trim();
        List<DbanInformation> dbanInformations = null;
        if (type.equals("图片") || type.equals("视频") || type.equals("音频")) {
            //图片资源、视频资源、音频资源：名称判断
            DbanInformation dbanInformation = new DbanInformation();
            dbanInformation.setType(type);
            dbanInformation.setName(name);
            dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
        } else if (type.equals("图书")) {
            //图书资源：图书名称+出版社
            String publisher = dbanInformationParam.getPublisher().trim();
            DbanInformation dbanInformation = new DbanInformation();
            dbanInformation.setType(type);
            dbanInformation.setName(name);
            dbanInformation.setPublisher(publisher);
            dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
        } else if (type.equals("文章")) {
            //文章：名称+刊物名称+刊发时间
            String publisher = dbanInformationParam.getPublisher().trim();
            String releaseDate = dbanInformationParam.getReleaseDate().trim();
            DbanInformation dbanInformation = new DbanInformation();
            dbanInformation.setType(type);
            dbanInformation.setName(name);
            dbanInformation.setPublisher(publisher);
            dbanInformation.setReleaseDate(releaseDate);
            dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
        } else if (type.equals("文件")) {
            //文件资源：文件号
            String bookName = dbanInformationParam.getBookName().trim();
            DbanInformation dbanInformation = new DbanInformation();
            dbanInformation.setType(type);
            dbanInformation.setBookName(bookName);
            dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
        } else if (type.equals("五个一批好成果")) {
            if (fiveOneType.equals("理论文章")) {
                //理论文章：名称+刊物名称+刊发时间
                String bookName = dbanInformationParam.getBookName().trim();
                String releaseDate = dbanInformationParam.getReleaseDate().trim();
                DbanInformation dbanInformation = new DbanInformation();
                dbanInformation.setType(type);
                dbanInformation.setFiveOneType(fiveOneType);
                dbanInformation.setName(name);
                dbanInformation.setBookName(bookName);
                dbanInformation.setReleaseDate(releaseDate);
                dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
            } else if (fiveOneType.equals("教学课程")) {
                //课程：名称+时间
                String releaseDate = dbanInformationParam.getReleaseDate().trim();
                DbanInformation dbanInformation = new DbanInformation();
                dbanInformation.setType(type);
                dbanInformation.setFiveOneType(fiveOneType);
                dbanInformation.setName(name);
                dbanInformation.setReleaseDate(releaseDate);
                dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
            } else if (fiveOneType.equals("咨询报告")) {
                //咨询报告：名称+载体+时间
                String releaseDate = dbanInformationParam.getReleaseDate().trim();
                String reportBody = dbanInformationParam.getReportBody().trim();
                DbanInformation dbanInformation = new DbanInformation();
                dbanInformation.setType(type);
                dbanInformation.setFiveOneType(fiveOneType);
                dbanInformation.setName(name);
                dbanInformation.setReportBody(reportBody);
                dbanInformation.setReleaseDate(releaseDate);
                dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
            } else if (fiveOneType.equals("教材")) {
                //教材：名称+出版社+时间
                String releaseDate = dbanInformationParam.getReleaseDate().trim();
                String publisher = dbanInformationParam.getPublisher().trim();
                DbanInformation dbanInformation = new DbanInformation();
                dbanInformation.setType(type);
                dbanInformation.setFiveOneType(fiveOneType);
                dbanInformation.setName(name);
                dbanInformation.setPublisher(publisher);
                dbanInformation.setReleaseDate(releaseDate);
                dbanInformations = dbanInformationMapper.queryDbanInfomationRepeat(dbanInformation);
            } else {
                throw new RuntimeException("==>五个一批好成果中没有此类型.");
            }
        } else {
            log.info("==>无此类型.");
            throw new RuntimeException("无此类型:" + type);
        }
        return dbanInformations;
    }

    @Override
    public int updateStatusBatch(Integer status, List<Integer> ids, String remark) {
        return dbanInformationMapper.updateStatusBatch(status, ids, remark);
    }

    @Override
    public int updateStatusById(Integer id, Integer status) {
        DbanInformation entity = new DbanInformation();
        entity.setId(id);
        entity.setStatus(status);
        int updateCount = dbanInformationMapper.updateById(entity);
        return updateCount;
    }

    /**
     * 事物去保存基础表单信息和文件信息表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveBaseInformatinAndFile(DbanInformation dbanInformation) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        String userId = sysUser.getId();
        String realname = sysUser.getRealname();
        List<String> departIdsByUsername = sysBaseApi.getDepartIdsByUsername(username);
        String departIds = String.join(",", departIdsByUsername);
        List<String> rolesByUsername = sysBaseApi.getRolesByUsername(username);
        String roles = String.join(",", rolesByUsername);
        dbanInformation.setRoles(roles);

        //===================================================================
        dbanInformation.setIsTop(1);
        dbanInformation.setTopId(0);

        if ("理论文章".equals(dbanInformation.getFiveOneType())){
            dbanInformation.setCategoryId(1);
        }else if ("咨询报告".equals(dbanInformation.getFiveOneType())){
            dbanInformation.setCategoryId(2);
        }else if ("教材".equals(dbanInformation.getFiveOneType())){
            dbanInformation.setCategoryId(3);
        }else if ("教学课程".equals(dbanInformation.getFiveOneType())){
            dbanInformation.setCategoryId(4);
        }

        if ("图片".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(5);
        }else if("视频".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(6);
        }else if("文件".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(7);
        }else if("文章".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(8);
        }else if("图书".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(9);
        }else if("音频".equals(dbanInformation.getType())){
            dbanInformation.setCategoryId(10);
        }

        if(!"".equals(dbanInformation.getFiveOneType())){
            dbanInformation.setMainCategory(1);
        }
        if(!"".equals(dbanInformation.getType())){
            dbanInformation.setMainCategory(2);
        }
        //===================================================================

        dbanInformation.setCreateUser(username);
        dbanInformation.setRealName(realname);
        dbanInformation.setCreateUserId(userId);
        dbanInformation.setDeptIds(departIds);
        dbanInformation.setUpdateTime(new Date());
        String releaseDate = dbanInformation.getReleaseDate();
        if (StringUtils.isNotBlank(releaseDate)) {
            String substring = releaseDate.trim().substring(0, 4);
            dbanInformation.setYear(Integer.parseInt(substring));
        }
        //添加基础信息表单
        int insertInfoCount = dbanInformationMapper.insert(dbanInformation);
        Integer id = dbanInformation.getId();
        //先处理文件
        String infoType = dbanInformation.getType();

        String type = this.getEnType(infoType);//如果是五个一好成果的话需要再细分
        MultipartFile[] files = dbanInformation.getFiles();
        if (files != null) {
            for(MultipartFile file : files){
                if(infoType.equals("五个一批好成果")){
                    String fiveOneType = dbanInformation.getFiveOneType();
                    String enFiveOneType = getEnFiveOneType(fiveOneType);
                    String path = String.format("%s/%s",type,enFiveOneType);
                    uploadFile(file,fiveOneType,id,path);
                }else{
                    uploadFile(file, infoType, id, type);
                }
            }
        }
        //如果是图数的话单独处理
        if (infoType.equals("图书")) {
            MultipartFile[] coverImages = dbanInformation.getCoverImage();
            if (coverImages != null) {
                for (MultipartFile fileItem : coverImages) {
                    String tushuPath = String.format("%s/coverImage", type);
                    uploadFile(fileItem, "封面图片", id, tushuPath);
                }
            }
            MultipartFile[] authorInfoImages = dbanInformation.getAuthorInfoImage();
            if (authorInfoImages != null) {
                for (MultipartFile fileItem : authorInfoImages) {
                    String tushuPath = String.format("%s/authorInfoImage", type);
                    uploadFile(fileItem, "作者简介图片", id, tushuPath);
                }
            }
            MultipartFile[] copyrightImages = dbanInformation.getCopyrightImage();
            if (copyrightImages != null) {
                for (MultipartFile fileItem : copyrightImages) {
                    String tushuPath = String.format("%s/copyrightImage", type);
                    uploadFile(fileItem, "版权页图片", id, tushuPath);
                }
            }
            MultipartFile[] directoryImages = dbanInformation.getDirectoryImage();
            if (directoryImages != null) {
                for (MultipartFile fileItem : directoryImages) {
                    String tushuPath = String.format("%s/directoryImage", type);
                    uploadFile(fileItem, "目录图片", id, tushuPath);
                }
            }
        }
        //如果是五个一批好成果中的理论文章和教材需要单独处理
        if (infoType.equals("五个一批好成果")) {
            String fiveOneType = dbanInformation.getFiveOneType();
            String enFiveOneType = getEnFiveOneType(fiveOneType);
            if (fiveOneType.equals("教材")) {
                MultipartFile[] coverImages = dbanInformation.getCoverImage();
                if (coverImages != null) {
                    for (MultipartFile fileItem : coverImages) {
                        String jiaoCaiPath = String.format("%s/%s/coverImage", type, enFiveOneType);
                        uploadFile(fileItem, "封面图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] authorInfoImages = dbanInformation.getAuthorInfoImage();
                if (authorInfoImages != null) {
                    for (MultipartFile fileItem : authorInfoImages) {
                        String jiaoCaiPath = String.format("%s/%s/authorInfoImage", type, enFiveOneType);
                        uploadFile(fileItem, "作者简介图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] copyrightImages = dbanInformation.getCopyrightImage();
                if (copyrightImages != null) {
                    for (MultipartFile fileItem : copyrightImages) {
                        String jiaoCaiPath = String.format("%s/%s/copyrightImage", type, enFiveOneType);
                        uploadFile(fileItem, "版权页图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] directoryImages = dbanInformation.getDirectoryImage();
                if (directoryImages != null) {
                    for (MultipartFile fileItem : directoryImages) {
                        String jiaoCaiPath = String.format("%s/%s/directoryImage", type, enFiveOneType);
                        uploadFile(fileItem, "目录图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] contentFiles = dbanInformation.getContentFile();
                if (contentFiles != null) {
                    for (MultipartFile fileItem : contentFiles) {
                        String jiaoCaiPath = String.format("%s/%s/contentFile", type, enFiveOneType);
                        uploadFile(fileItem, "全文", id, jiaoCaiPath);
                    }
                }
            }
            if (fiveOneType.equals("教学课程")) {
                MultipartFile[] lessonVideos = dbanInformation.getLessonVideo();
                if (lessonVideos != null) {
                    for (MultipartFile fileItem : lessonVideos) {
                        String jiaoCaiPath = String.format("%s/%s/lessonVideo", type, enFiveOneType);
                        uploadFile(fileItem, "课程视频", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] lessonppts = dbanInformation.getLessonppt();
                if (lessonppts != null) {
                    for (MultipartFile fileItem : lessonppts) {
                        String jiaoCaiPath = String.format("%s/%s/lessonppt", type, enFiveOneType);
                        uploadFile(fileItem, "课程PPT", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] speechFiles = dbanInformation.getSpeechFile();
                if (speechFiles != null) {
                    for (MultipartFile fileItem : speechFiles) {
                        String jiaoCaiPath = String.format("%s/%s/speechFile", type, enFiveOneType);
                        uploadFile(fileItem, "演讲稿", id, jiaoCaiPath);
                    }

                }
            }
        }
        return insertInfoCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editInformation(DbanInformation dbanInformation) {

        //判断删除文件id集合不为空，那就批量删除
        String deleteFileIds = dbanInformation.getDeleteFileIds();
        if (StringUtils.isNotBlank(deleteFileIds)) {
            String[] splitIds = deleteFileIds.split(",");
            List<String> idsStrList = Arrays.asList(splitIds);
            List<Integer> integerList = idsStrList.stream().map(Integer::parseInt).collect(Collectors.toList());
            log.info("==>xuyaoshanchu:{}", integerList);
            dbanFileNginxMapper.deleteByIds(integerList);
        }

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        String userId = sysUser.getId();
        dbanInformation.setCreateUser(username);
        dbanInformation.setCreateUserId(userId);
        String releaseDate = dbanInformation.getReleaseDate();
        if (StringUtils.isNotBlank(releaseDate)) {
            String substring = releaseDate.trim().substring(0, 4);
            dbanInformation.setYear(Integer.parseInt(substring));
        }
        //修改更新数据库
        int updateCount = dbanInformationMapper.updateById(dbanInformation);
        Integer id = dbanInformation.getId();
        //先处理文件
        String infoType = dbanInformation.getType();
        String type = this.getEnType(infoType);//如果是五个一好成果的话需要再细分
        MultipartFile[] files = dbanInformation.getFiles();
        if (files != null) {
            for (MultipartFile file : files) {
                if (infoType.equals("五个一批好成果")) {
                    String fiveOneType = dbanInformation.getFiveOneType();
                    String enFiveOneType = getEnFiveOneType(fiveOneType);
                    String path = String.format("%s/%s", type, enFiveOneType);
                    uploadFile(file, fiveOneType, id, path);
                } else {
                    uploadFile(file, infoType, id, type);
                }
            }
        }
        //图书单独处理
        if (infoType.equals("图书")) {
            MultipartFile[] coverImages = dbanInformation.getCoverImage();
            if (coverImages != null) {
                for (MultipartFile fileItem : coverImages) {
                    String tushuPath = String.format("%s/coverImage", type);
                    uploadFile(fileItem, "封面图片", id, tushuPath);
                }
            }

            MultipartFile[] authorInfoImages = dbanInformation.getAuthorInfoImage();
            if (authorInfoImages != null) {
                for (MultipartFile fileItem : authorInfoImages) {
                    String tushuPath = String.format("%s/authorInfoImage", type);
                    uploadFile(fileItem, "作者简介图片", id, tushuPath);
                }
            }
            MultipartFile[] copyrightImages = dbanInformation.getCopyrightImage();
            if (copyrightImages != null) {
                for (MultipartFile fileItem : copyrightImages) {
                    String tushuPath = String.format("%s/copyrightImage", type);
                    uploadFile(fileItem, "版权页图片", id, tushuPath);
                }
            }
            MultipartFile[] directoryImages = dbanInformation.getDirectoryImage();
            if (directoryImages != null) {
                for (MultipartFile fileItem : directoryImages) {
                    String tushuPath = String.format("%s/directoryImage", type);
                    uploadFile(fileItem, "目录图片", id, tushuPath);
                }
            }
        }
        //如果是五个一批好成果中的理论文章和教材需要单独处理
        if (infoType.equals("五个一批好成果")) {
            String fiveOneType = dbanInformation.getFiveOneType();
            String enFiveOneType = getEnFiveOneType(fiveOneType);
            if (fiveOneType.equals("教材")) {
                MultipartFile[] coverImages = dbanInformation.getCoverImage();
                if (coverImages != null) {
                    for (MultipartFile fileItem : coverImages) {
                        String jiaoCaiPath = String.format("%s/%s/coverImage", type, enFiveOneType);
                        uploadFile(fileItem, "封面图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] authorInfoImages = dbanInformation.getAuthorInfoImage();
                if (authorInfoImages != null) {
                    for (MultipartFile fileItem : authorInfoImages) {
                        String jiaoCaiPath = String.format("%s/%s/authorInfoImage", type, enFiveOneType);
                        uploadFile(fileItem, "作者简介图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] copyrightImages = dbanInformation.getCopyrightImage();
                if (copyrightImages != null) {
                    for (MultipartFile fileItem : copyrightImages) {
                        String jiaoCaiPath = String.format("%s/%s/copyrightImage", type, enFiveOneType);
                        uploadFile(fileItem, "版权页图片", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] directoryImages = dbanInformation.getDirectoryImage();
                if (directoryImages != null) {
                    for (MultipartFile fileItem : directoryImages) {
                        String jiaoCaiPath = String.format("%s/%s/directoryImage", type, enFiveOneType);
                        uploadFile(fileItem, "目录图片", id, jiaoCaiPath);
                    }
                }
//                MultipartFile[] contentFiles = dbanInformation.getContentFile();
//                if (contentFiles != null) {
//                    for (MultipartFile fileItem : contentFiles) {
//                        String jiaoCaiPath = String.format("%s/%s/contentFile", type, enFiveOneType);
//                        uploadFile(fileItem, "全文", id, jiaoCaiPath);
//                    }
//                }
            }
            if (fiveOneType.equals("教学课程")) {
                MultipartFile[] lessonVideos = dbanInformation.getLessonVideo();
                if (lessonVideos != null) {
                    for (MultipartFile fileItem : lessonVideos) {
                        String jiaoCaiPath = String.format("%s/%s/lessonVideo", type, enFiveOneType);
                        uploadFile(fileItem, "课程视频", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] lessonppts = dbanInformation.getLessonppt();
                if (lessonppts != null) {
                    for (MultipartFile fileItem : lessonppts) {
                        String jiaoCaiPath = String.format("%s/%s/lessonppt", type, enFiveOneType);
                        uploadFile(fileItem, "课程PPT", id, jiaoCaiPath);
                    }
                }
                MultipartFile[] speechFiles = dbanInformation.getSpeechFile();
                if (speechFiles != null) {
                    for (MultipartFile fileItem : speechFiles) {
                        String jiaoCaiPath = String.format("%s/%s/speechFile", type, enFiveOneType);
                        uploadFile(fileItem, "演讲稿", id, jiaoCaiPath);
                    }

                }
            }
        }

        return updateCount;
    }

    @Override
    public Map<String, Object> getConditions(String type) {

        Map<String,Object> map = new LinkedHashMap<>(3);
        map.put("status",statusMap());
        Map<String, String[]> parameterMap = new HashMap<>(1);
        DbanInformation dbanInformation = new DbanInformation();
        dbanInformation.setType(type);
        List<DbanInformation> informations = dbanInformationMapper.queryDbanInfomation(dbanInformation);
        Set<String> locationSet = new HashSet<>();
        Set<String> subjectSet = new HashSet<>();
        for(DbanInformation index : informations){
            locationSet.add(index.getLocation());
            subjectSet.add(index.getSubject());
        }
        //发布地点
        List<String> locationList = new ArrayList<>(locationSet);
        List<Map<String,Object>> locationMapList = new ArrayList<>();
        for (String index : locationList) {
            Map<String,Object> locationMap = new LinkedHashMap<>(2);
            locationMap.put("name",index);
            locationMap.put("value",index);
            locationMapList.add(locationMap);
        }
        //主题
        List<String> subjectList = new ArrayList<>(subjectSet);
        List<Map<String,Object>> subjectnMapList = new ArrayList<>();
        for (String index : subjectList) {
            Map<String,Object> subjectMap = new LinkedHashMap<>(2);
            subjectMap.put("name",index);
            subjectMap.put("value",index);
            subjectnMapList.add(subjectMap);
        }
        map.put("location",locationList);
        map.put("subject",subjectList);
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Integer id) {
        //删除主信息
        int deleteInfoCount = dbanInformationMapper.deleteById(id);
        //删除附件信息
        int deleteFileCount = dbanFileNginxMapper.deleteByInfoId(id);
        return deleteInfoCount != 0 && deleteFileCount != 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitInfo(Integer id, Integer status, String remark, Integer version) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        String realName = sysUser.getRealname();
        String userId = sysUser.getId();
        List<String> departIdsByUsername = sysBaseApi.getDepartIdsByUsername(username);
        String departIds = String.join(",", departIdsByUsername);
        //更新主数据
        //-1 待提审
        //0	审核中
        //1	审核通过
        //2	审核未通过
        DbanInformation entity = new DbanInformation();
        entity.setId(id);
        entity.setStatus(status);
        if (status == 1) {
            entity.setCxversion(version);
        }
        entity.setLatestAuditUserId(userId); //记录最后审核人信息，供查询使用
        entity.setUpdateTime(new Date());
        int updateCount = dbanInformationMapper.updateById(entity);
        //添加到审核和提交记录表中去
        DbanAuthRecord record = new DbanAuthRecord();
        record.setPkId(id);
        record.setUserId(userId);
        record.setRealName(realName);
        record.setUserName(username);
        record.setDeptIds(departIds);
        List<String> roles = sysBaseApi.getRolesByUsername(username);
        if (roles.contains("province_asset_audit") || roles.contains("province_asset_edit")) {
            log.info("==>省人员");
            record.setStatusTxt(getStatusTxt(status, "省人员"));
        } else {
            log.info("==>地级人员");
            record.setStatusTxt(getStatusTxt(status, "地级人员"));
        }

        record.setOperTime(new Date());
        if (StringUtils.isNoneBlank(remark)) {
            record.setRemark(remark);
        }
        int insertCount = dbanAuthRecordMapper.insert(record);
        return updateCount != 0 && insertCount != 0;
    }

    @Override
    public int addViewCount(Integer id) {
        return dbanInformationMapper.addViewCount(id);
    }

    /**
     * 校长删除数据
     */
    @Override
    public String deleteByPresident(Integer id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = sysUser.getUsername();
        List<String> roles = sysBaseApi.getRolesByUsername(username);
        if (roles.contains("dx_president")) {
            dbanInformationMapper.deleteById(id);
            dbanAuthRecordMapper.deleteByPkId(id);
            return "删除成功.";
        } else {
            return " 没有权限删除.";
        }
    }


    /**
     * 待提审	-1
     * 市审核员审核中	0
     * 省审核员审核中	1
     * 省审核未通过	2
     * 审核成功	3
     * 市审核未通过4
     * 市审核未通过4撤销->变成市审核员审核中0
     * 发布成功3撤销->变成省审核员审核中1->撤销->变成市审核员审核中0
     * 省审核未通过2撤销->省审核员审核中1->撤销->变成市审核员审核中0
     * @param status
     * @return
     */

    private String getStatusTxt(Integer status, String type) {
        // 0-提交审核 1-审核通过 2-审核拒绝
        if (status == -1) {
            return "待审核";
        } else if (status == 0) {
            return "提交审核";//"市审核员审核中"; 市录入员操作
        } else if (status == 1) {
            if (type.equals("省人员")) {
                return "省录入员提交审核，省审核员审核中";
            } else {
                return "市审核员审核通过，省审核员审核中";
            }
            //市审核员操作 如果是省录入员的话：省录入员提交审核，省审核员审核中

        } else if (status == 2) {
            return "省审核未通过";//省审核员操作的
        } else if (status == 3) {
            return "审核成功";//省审核员
        } else if (status == 4) {
            return "市审核未通过";//市审核员
        } else if (status == 900) {
            return "备选入库";//省审核员
        } else {
            throw new RuntimeException("==>无此参数");
        }
    }


    /**
     * 上传文件
     */
    private void uploadFile(MultipartFile file,String infoType,Integer id,String path){
        log.info("=================================>进入uploadFile");
        String filename = file.getOriginalFilename();
        long size = file.getSize();
        String subfilename = filename.substring(0, filename.lastIndexOf("."));
        String suffix = filename.substring(filename.lastIndexOf("."));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        String  dirPath = String.format("%s/%s/%s/%s", nginxDir, nginxFileDir, path, format);
        String  dirFile = String.format("%s/%s", dirPath, filename);
        String url = String.format("/%s/%s/%s/%s", nginxFileDir, path, format, filename);
        DbanFileNginx dbanFileNginx = new DbanFileNginx();
        dbanFileNginx.setFileName(subfilename);
        dbanFileNginx.setFileSize(size);
        dbanFileNginx.setType(infoType);
        dbanFileNginx.setFileSuffix(suffix);
        dbanFileNginx.setDiskPath(dirFile);
        dbanFileNginx.setFilePath(url);
        dbanFileNginx.setInfoId(id);
        //添加到硬盘
        try {
            InputStream inputStream = file.getInputStream();
            FileUtils.addFileToDisk(inputStream,dirPath,filename);
        } catch (Exception e) {
            log.error("==>上传文件失败.");
            throw new RuntimeException("上传文件失败");
        }
        log.info("=================================>开始insert file 表 进入{}", infoType);
        dbanFileNginxMapper.insert(dbanFileNginx);
        log.info("=================================结束insert file 表 进入{}", infoType);
    }

    /**
     * 状态查询条件
     */
    private List<Map<String,Object>> statusMap(){
        List<Map<String,Object>> list = new ArrayList<>();
        for (DbanInfoStatusEnum index : DbanInfoStatusEnum.values()) {
            Map<String,Object> map = new LinkedHashMap<>(2);
            map.put("name",index.displayName());
            map.put("value",index.value());
            list.add(map);
        }
        return list;
    }


    /**
     * 文章 图片 图书 视频 音频 五个一好成果
     * 根据type拿到对应的英文
     */
    private String getEnType(String type){

        if(type.equals("文章")){
            return "article";
        } else if (type.equals("文件")) {
            return "file";
        }else if(type.equals("图片")){
            return "image";
        }else if(type.equals("图书")){
            return "imagebook";
        }else if(type.equals("视频")){
            return "video";
        }else if(type.equals("音频")){
            return "voice";
        }else if(type.equals("五个一批好成果")){
            return "goodresult";
        }else{
            throw new RuntimeException("==>没有此类型.");
        }
    }

    private String getEnFiveOneType(String fiveOneType){
        if(fiveOneType.equals("理论文章")){
            return "article";
        }else if(fiveOneType.equals("教学课程")){
            return "lesson";
        }else if(fiveOneType.equals("咨询报告")){
            return "report";
        }else if(fiveOneType.equals("教材")){
            return "book";
        }else{
            throw new RuntimeException("==>没有此类型.");
        }
    }


    /**
     * 更新主表审核人信息
     */
    public int updateUserInfo() {
        DbanInformation dbanInformation = new DbanInformation();
        List<DbanInformation> dbanInformations = dbanInformationMapper.queryDbanInfomation(dbanInformation);
        for (DbanInformation index : dbanInformations) {
            Integer pkId = index.getId();
            DbanAuthRecord dbanAuthRecord = dbanAuthRecordMapper.findOne(pkId);
            if (dbanAuthRecord != null) {
                String userId = dbanAuthRecord.getUserId();
                DbanInformation information = new DbanInformation();
                information.setLatestAuditUserId(userId);
                int updated = dbanInformationMapper.updateById(information);
                log.info("==>数据已{}更新...", index.getId());
            }

        }
        return 1;
    }

    //=============================================================================================
    /**
     * 查询置顶列表
     * */
    @Override
    public List<DbanInformation> queryDbanInformationByTop(Integer isTop) {
        return dbanInformationMapper.queryDbanInformationByTop(isTop);
    }

    /**
     * 更新是否置顶
     * */
    @Override
    public int updateDbanInformationTop(Integer id,
                                        Integer topId,
                                        Integer isTop) {

        DbanInformation dbanInformation = new DbanInformation();
        dbanInformation.setTopId(topId);
        dbanInformation.setIsTop(isTop);

        QueryWrapper<DbanInformation> wrapper=new QueryWrapper<>();
        wrapper.eq("id",id);
        int updateDbanInfo= dbanInformationMapper.update(dbanInformation, wrapper);

        return updateDbanInfo;
    }

    /**
     * 基础资源库置顶排序
     * 置顶排序根据需要正序排序
     * 相同置顶序号的数据以时间倒叙排列
     * */
    @Override
    public IPage<DbanInformation> queryBaseDbanInformationByTop(Integer pageNo,
                                                                Integer pageSize,
                                                                String type,
                                                                Integer isTop) {

        List<DbanInformation> videoList = null;
        List<DbanInformation> audioList= null;
        List<DbanInformation> fileList= null;
        List<DbanInformation> wordList= null;
        List<DbanInformation> picList= null;
        List<DbanInformation> bookList = null;

        String[] items = type.split(",");
        for (String item : items){
            if("视频".equals(item)){
                videoList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }else if("音频".equals(item)){
                audioList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }else if("文件".equals(item)){
                fileList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }else if("文章".equals(item)){
                wordList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }else if("图片".equals(item)){
                picList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }else if("图书".equals(item)){
                bookList = dbanInformationMapper.queryBaseDbanInformationByTop(item,isTop);
            }
        }

        List<DbanInformation> dbanInformationList = Stream.of(videoList, audioList, fileList, wordList, picList, bookList)
                .filter(list -> list != null)
                .flatMap(list -> list.stream())
                .sorted(Comparator.comparing(DbanInformation::getTopId)
                        .thenComparing(DbanInformation::getCreateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());

        IPage<DbanInformation> page = PageUtil.convertListToIPage(dbanInformationList,pageNo,pageSize);
        return page;
    }

    /**
     * 五个一批好成果置顶排序
     * 置顶排序根据需要正序排序
     * 相同置顶序号的数据以时间倒叙排列
     * */
    @Override
    public IPage<DbanInformation> queryFiveOndDbanInformationByTop(Integer pageNo,
                                                                   Integer pageSize,
                                                                   String fiveOneType,
                                                                   Integer isTop) {

        List<DbanInformation> theoreticalArticlesList = null;
        List<DbanInformation> consultationReportList= null;
        List<DbanInformation> teachingMaterialList= null;
        List<DbanInformation> teachingCoursesList= null;

        String[] items = fiveOneType.split(",");
        for (String item : items){
            if("理论文章".equals(item)){
                theoreticalArticlesList = dbanInformationMapper.queryFiveOneDbanInformationByTop(item,isTop);
            }else if("咨询报告".equals(item)){
                consultationReportList = dbanInformationMapper.queryFiveOneDbanInformationByTop(item,isTop);
            }else if("教材".equals(item)){
                teachingMaterialList = dbanInformationMapper.queryFiveOneDbanInformationByTop(item,isTop);
            }else if("教学课程".equals(item)){
                teachingCoursesList = dbanInformationMapper.queryFiveOneDbanInformationByTop(item,isTop);
            }
        }
        List<DbanInformation> dbanInformationList = Stream.of(theoreticalArticlesList, consultationReportList, teachingMaterialList, teachingCoursesList)
                .filter(list -> list != null)
                .flatMap(list -> list.stream())
                .sorted(Comparator.comparing(DbanInformation::getTopId)
                        .thenComparing(DbanInformation::getCreateTime, Comparator.reverseOrder()))
                .collect(Collectors.toList());

        IPage<DbanInformation> page = PageUtil.convertListToIPage(dbanInformationList,pageNo,pageSize);

        return page;
    }

    @Override
    public List<DbanInformation> queryBaseDbanInformationByTopList(String type, Integer isTop) {
        return dbanInformationMapper.queryBaseDbanInformationByTop(type,isTop);
    }

    @Override
    public IPage<DbanInformation> queryBaseResouceDbanInformation(Integer pageNo, Integer pageSize, String type, Integer isTop) {


        return null;
    }

    @Override
    public IPage<DbanInformation> queryFiveOneDbanInformation(Integer pageNo, Integer pageSize, String fiveOneType, Integer isTop) {

        return null;
    }

    @Override
    public IPage<DbanInformationDto> queryFiveOneTopDbanInformationByStatus(Integer pageNo,
                                                                            Integer pageSize,
                                                                            Integer mainCategory,
                                                                            String status,
                                                                            Integer isTop) {

        MPJLambdaWrapper wrapper = new MPJLambdaWrapper<DbanInformationDto>()
                .selectAll(DbanInformationDto.class)
                .select(DbanAuthRecord::getPkId)
                .select(DbanAuthRecord::getOperTime)
                .leftJoin(DbanAuthRecord.class,DbanAuthRecord::getPkId,DbanInformation::getId)
                .eq(DbanInformation::getStatus,status)
                .eq(DbanInformation::getIsTop,isTop)
                .eq(DbanInformation::getMainCategory,1);

        IPage<DbanInformationDto> commentDtoIPageList = dbanInformationMapper.selectJoinPage(new Page<>(pageNo, pageSize),DbanInformationDto.class,wrapper);

//        List<DbanInformationDto> list = dbanInformationMapper.selectJoinList(DbanInformationDto.class, wrapper);

        return commentDtoIPageList;
    }
    //=============================================================================================
}
